/*
 * 全局公用方法
 */
import Vue from 'vue'
import Store from '@/store/store';
// import common from "@/common/js/common.js";
import {
	$api
} from '@/config/api.js';
import md5 from 'js-md5'
var xwPluginModule = uni.requireNativePlugin("XwPlugin")
console.log(xwPluginModule, 'moduless')

export default {

	//登出
	logOut() {       
	    // $api.get('/user/logout')
		// 清空本地存储的登录数据
		uni.setStorageSync('mem-username', '')
		uni.setStorageSync('mem-password', '')
		uni.setStorageSync('sms-mobile', '')
		uni.setStorageSync('mem-openid', '')
		Store.commit('setInit', {});
		Store.commit('setLoginInfo', {});
		Store.commit('setUserInfo', {});
		Store.commit('setSelectedGame', '')
		return
	},
	// 获取用户信息
	getuserInfo() {
		return $api.get("/user/detail").then(res => {
			let username = uni.getStorageSync('mem-username')||uni.getStorageSync('sms-mobile');
			if (res.data.code == 200) {
				// 当记录的用户登录账户与登录之后返回的账户不匹配时，就不允许登录成功
				if (username == res.data.data.mobile || username == res.data.data.username) {
					getApp().globalData.store.commit('setUserInfo', res.data.data);
				} else {	
			    this.logOut()
				}
			} else {
				this.logOut()

			}
		})
	},
	// 获取多游信息
	getDYInfo(){
		let param = null;
		let Store = getApp().globalData.store;
		// console.log('信息',Store.state.userInfo,'deviceidinfo',Store.state.deviceidinfo)
		param = {
			'media_id' : uni.getSystemInfoSync().platform == 'ios' ? Store.state.dyInfo.ios_media_id : Store.state.dyInfo.media_id,
			'user_id' : (Store.state.userInfo && Store.state.userInfo.mem_id) ? Store.state.userInfo.mem_id : 10000,
			'device_type' : uni.getSystemInfoSync().platform == 'ios' ? '1' : '2',
			'key' : uni.getSystemInfoSync().platform == 'ios' ? Store.state.dyInfo.ios_key : Store.state.dyInfo.key,
			'device_ids' : encodeURIComponent(JSON.stringify({
				"1":Store.state.deviceidinfo.IMEI,
				"7":Store.state.deviceidinfo.OAID,
				"4":Store.state.deviceidinfo.idfa
			}))
		}
		let sign = md5('device_ids='+ param.device_ids + '&device_type=' + param.device_type +'&media_id=' + param.media_id + '&user_id='+ param.user_id +'&key=' + param.key)
		param.sign = sign
		return param
	},
	// 获取系统是否授权设备id(试玩)
	isAuthorized_deviceinfo(){
		let platform = uni.getSystemInfoSync().platform;
		let Store = getApp().globalData.store;
		let flag = false;
		if(platform == 'android'){
			console.log('Store',Store.state.deviceidinfo);
			if(Store.state.deviceidinfo && (Store.state.deviceidinfo.OAID || Store.state.deviceidinfo.IMEI)){
				flag = true;
			}else{
				uni.showModal({
					title:'提示',
					content: '为保证您正常、安全地使用，需要获取设备识别码（部分手机提示为获取手机号码）使用权限，请允许，打开后请重新启动app',
					confirmText:'前往',
					confirmColor:'#0055ff',
					success: res=> {
						if (res.confirm) {
							this.gotoAppPermissionSetting(1)
						}
					}
				})
			}
		}else{
			console.log('Store2>>>',Store.state.deviceidinfo);
			if(Store.state.deviceidinfo && Store.state.deviceidinfo.idfa == '00000000-0000-0000-0000-000000000000'){
				uni.showModal({
					title:'提示',
					content: '请前往设置-隐私-跟踪允许App请求跟踪，打开后请重新启动app',
					confirmText:'前往',
					confirmColor:'#0055ff',
					success: res=> {
						if (res.confirm) {
							this.gotoAppPermissionSetting(2)
						}
					}
				})
			}else{
				flag = true;
			}
		}
		return flag
	},
	gotoAppPermissionSetting(type){
		if (type == 2) {
			var UIApplication = plus.ios.import("UIApplication");
			var application2 = UIApplication.sharedApplication();
			var NSURL2 = plus.ios.import("NSURL");
			var setting2 = NSURL2.URLWithString("app-settings:");
			application2.openURL(setting2);
		
			plus.ios.deleteObject(setting2);
			plus.ios.deleteObject(NSURL2);
			plus.ios.deleteObject(application2);
		} else {
			var Intent = plus.android.importClass("android.content.Intent");
			var Settings = plus.android.importClass("android.provider.Settings");
			var Uri = plus.android.importClass("android.net.Uri");
			var mainActivity = plus.android.runtimeMainActivity();
			var intent = new Intent();
			intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
			var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
			intent.setData(uri);
			mainActivity.startActivity(intent);
		}
	},
	
	number(value) {
		return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
	},
	
	getPx(value, unit = false) {
		if (this.number(value)) {
			return unit ? `${value}px` : Number(value)
		}
		// 如果带有rpx，先取出其数值部分，再转为px值
		if (/(rpx|upx)$/.test(value)) {
			return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value)))
		}
		return unit ? `${parseInt(value)}px` : parseInt(value)
	},

	//获取节点
	getEl(el) {
		if (typeof el === 'string' || typeof el === 'number') return el;
		if (WXEnvironment) {
			return el.ref;
		} else {
			return el instanceof HTMLElement ? el : el.$el;
		}
	},
	// 节流函数：规定在一个单位时间内，只能触发一次函数。如果这个单位时间内触发多次函数，只有一次生效
	// throttle(canRun, func, wait) {
	// 	return function() {
	// 		console.log(canRun, 'canRuncanRun')
	// 		if (!canRun) return;
	// 		canRun = false;
	// 		setTimeout(() => {
	// 			func.apply(this, arguments);
	// 			canRun = true;
	// 			return canRun;
	// 		}, wait);
	// 		return canRun;
	// 	};
	// },
	// 判断是否登录，评论时需要先登录
	isLogin() {	
		if (Object.keys(getApp().globalData.store.state.userInfo).length == 0) {
			uni.showToast({
				title: '您还未登录，快去登录吧~',
				icon: 'none',
				success: () => {
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/my/children/login',
						})
						return false;
					}, 600)
				}
			})
		} else {
			return true;
		}
	},

	//复制 
	copyText(text) {
		uni.setClipboardData({
			data: text,
		})
	},
	/* 深拷贝 */
	getClone(obj) {
		if (obj === null) return null
		if (typeof obj !== 'object') return obj;
		if (obj.constructor === Date) return new Date(obj);
		if (obj.constructor === RegExp) return new RegExp(obj);
		var newObj = new obj.constructor(); //保持继承链
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) { //不遍历其原型链上的属性
				var val = obj[key];
				// newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; // 使用arguments.callee解除与函数名的耦合
			}
		}
		return newObj;
	},
	// 预览图片
	previewImage(index, arr) {
		//uniapp预览图片
		uni.previewImage({
			current: index, //预览图片的下标
			urls: arr, //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
			indicator: 'number'
		});
	},
	getNatve() {
		const infoSync = Store.state.infoSync
		const system = Store.state.infoSync.platform
		console.log(infoSync, 'infoSync')
		const navheight = 0


	},
	gaussBlur(imgData) {
		var pixes = imgData.data;
		var width = imgData.width;
		var height = imgData.height;
		var gaussMatrix = [],
			gaussSum = 0,
			x, y,
			r, g, b, a,
			i, j, k, len;

		var radius = 10;
		var sigma = 5;

		a = 1 / (Math.sqrt(2 * Math.PI) * sigma);
		b = -1 / (2 * sigma * sigma);
		//生成高斯矩阵
		for (i = 0, x = -radius; x <= radius; x++, i++) {
			g = a * Math.exp(b * x * x);
			gaussMatrix[i] = g;
			gaussSum += g;

		}

		//归一化, 保证高斯矩阵的值在[0,1]之间
		for (i = 0, len = gaussMatrix.length; i < len; i++) {
			gaussMatrix[i] /= gaussSum;
		}
		//x 方向一维高斯运算
		for (y = 0; y < height; y++) {
			for (x = 0; x < width; x++) {
				r = g = b = a = 0;
				gaussSum = 0;
				for (j = -radius; j <= radius; j++) {
					k = x + j;
					if (k >= 0 && k < width) { //确保 k 没超出 x 的范围
						//r,g,b,a 四个一组
						i = (y * width + k) * 4;
						r += pixes[i] * gaussMatrix[j + radius];
						g += pixes[i + 1] * gaussMatrix[j + radius];
						b += pixes[i + 2] * gaussMatrix[j + radius];
						// a += pixes[i + 3] * gaussMatrix[j];
						gaussSum += gaussMatrix[j + radius];
					}
				}
				i = (y * width + x) * 4;
				// 除以 gaussSum 是为了消除处于边缘的像素, 高斯运算不足的问题
				// console.log(gaussSum)
				pixes[i] = r / gaussSum;
				pixes[i + 1] = g / gaussSum;
				pixes[i + 2] = b / gaussSum;
				// pixes[i + 3] = a ;
			}
		}
		//y 方向一维高斯运算
		for (x = 0; x < width; x++) {
			for (y = 0; y < height; y++) {
				r = g = b = a = 0;
				gaussSum = 0;
				for (j = -radius; j <= radius; j++) {
					k = y + j;
					if (k >= 0 && k < height) { //确保 k 没超出 y 的范围
						i = (k * width + x) * 4;
						r += pixes[i] * gaussMatrix[j + radius];
						g += pixes[i + 1] * gaussMatrix[j + radius];
						b += pixes[i + 2] * gaussMatrix[j + radius];
						// a += pixes[i + 3] * gaussMatrix[j];
						gaussSum += gaussMatrix[j + radius];
					}
				}
				i = (y * width + x) * 4;
				pixes[i] = r / gaussSum;
				pixes[i + 1] = g / gaussSum;
				pixes[i + 2] = b / gaussSum;
			}
		}
		return imgData;
	},

	//
	setVideoUrl(url) {
		// return url;
		if (url && (url.indexOf('rs.wormhole00.com') == -1)) {
			return url;
		}
		
		// console.log(url,'mp4_url');
		let arr = url.split('?');
		// console.log(arr[0],'arr');
		
		
		let arr1 = arr[0].split('com');
		// console.log(arr1[1], 'arr1');
		
		let time = Date.parse( new Date());//获取到毫秒的时间戳，精确到毫秒
		// console.log(time, 'time');
		time = time / 1000;//精确到秒
		// console.log(time, 'time');
		
		const newUrl = arr1[1] + '-' + time.toString() + '-0-0-' + Store.state.auth_key + '5vk33mpbbot9hvcfiw';
		// console.log(newUrl, 'newUrl');
		
		const newUrl_md5 = md5(newUrl);
		// console.log(newUrl_md5, 'newUrl_md5');
		
		const videoUrl = arr1[0] + 'com' + arr1[1] + '?auth_key=' + time.toString() + '-0-0-' + newUrl_md5;
		// console.log(videoUrl, 'videoUrl');

		return videoUrl;
	},

	// 随机字符串
	randomString(len) {
		len = len || 32;
		let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		let maxPos = $chars.length;
		let pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	},

	// 生成下载鉴权sign
	downLoadUrl_sign() {
		let key = 'QyWbpzcfbJgtppSA';
		let code = this.randomString(5);
		let timestamp = Date.parse(new Date()) / 1000;
		let sign_key = String(timestamp.toString() + key + code);
		let sign1 = md5(code + timestamp + sign_key);
		let sign = code + '-' + timestamp + '-' + sign1;
		return sign;
	},
	
	//获取设备信息及oaid需先调用注册函数
	registerAsyncFunc(){
		let Store = getApp().globalData.store;
		console.log('注册',uni.getSystemInfoSync().platform);
		console.log('xwPluginModule',xwPluginModule);
		switch(uni.getSystemInfoSync().platform) {
			case "android":
				xwPluginModule.registerAsyncFunc(
					res=>{
						console.log(res,'执行安卓方法');
						setTimeout(()=>{					
							this.getdeviceinfoFunc()
							this.getdeviceidinfoFunc()
						},300)
					}
				)
				break;
			case "ios":
				console.log('执行IOS方法1122');
				xwPluginModule.getDeviceInfoAsyncFunc({},
					res=>{
						let deviceinfo = res
						console.log('deviceinfo',deviceinfo);
						// if(!deviceinfo || deviceinfo.idfa == '00000000-0000-0000-0000-000000000000'){
						// 	uni.showModal({
						// 		title:'提示',
						// 		content: '请前往设置-隐私-跟踪允许App请求跟踪，打开后请重新启动app',
						// 		confirmText:'前往',
						// 		showCancel:false,
						// 		confirmColor:'#0055ff',
						// 		success: function (res) {
						// 			if (res.confirm) {
						// 				console.log('res',res);
						// 				var app = plus.ios.invoke('UIApplication', 'sharedApplication');  
						// 				var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');  
						// 				plus.ios.invoke(app, 'openURL:', setting);  
						// 				plus.ios.deleteObject(setting);  
						// 				plus.ios.deleteObject(app);  
						// 			}
						// 		}
						// 	})
						// }
						console.log('deviceinfo',deviceinfo);
						Store.commit('setDeviceIdInfo', deviceinfo);
					}
				);
				break;
			default:
				break;
		}
	},
	//获取设备手机信息
	getdeviceinfoFunc(){
		xwPluginModule.deciceinfoAsyncFunc(res => {
			console.log(res);
			let deviceinfo = JSON.parse(res.deviceinfo)
			Store.commit('setDeviceInfo', deviceinfo);
		});
	},
	//获取设备id相关信息
	getdeviceidinfoFunc(){
		xwPluginModule.deciceidAsyncFunc(res => {
			if(res.oaidgetcomplet){
				console.log(res);
				let deviceid = JSON.parse(res.deviceid)
				Store.commit('setDeviceIdInfo', deviceid);
				$api.get("system/appinit",{
					'device_imei':deviceid.IMEI,
					'device_oaid':deviceid.OAID
				}).then(res => {
				})
			}
		});
	}


}
